// smsemu.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "smsemu.h"
#include "SMS.h"
#include "dx7video.h"

#define MAX_LOADSTRING 100

#define IDC_MAIN_STATUS	103

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

// Forward declarations of functions included in this code module:
int quit = 0;
int running = 0;
HWND hwnd = 0;
HACCEL hAccelTable = 0;
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	AboutProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	DebuggerProc(HWND, UINT, WPARAM, LPARAM);

char curdir[MAX_PATH] = "\0\0\0";
static char logfilename[1024] = "\0\0\0";
FILE *logfd = 0;

CDX7Video dx7;
CSMS sms;

void message(char *str,...)
{
	char buffer[512];					//buffer to store vsprintf'd message in
	va_list argptr;					//argument data

	va_start(argptr,str);			//get data
	vsprintf(buffer,str,argptr);	//print to buffer
	va_end(argptr);					//done!
	if(logfd) {
		fprintf(logfd,buffer);
		fflush(logfd);
	}
	SendDlgItemMessage(hwnd,IDC_MAIN_STATUS,SB_SETTEXT,1,(LPARAM)buffer);
}

void CheckMessages()
{
	MSG msg;

	while(PeekMessage(&msg,0,0,0,PM_REMOVE)) {
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
}

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.

	//make log filename
	GetCurrentDirectory(MAX_PATH,curdir);
	sprintf(logfilename,"%s\\smsemu.log",curdir);

	//init log
	if((logfd = fopen(logfilename,"wt")) == 0) {
		message("error opening log file\n");
	}

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_SMSEMU, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	if(sms.Load(lpCmdLine) == 0) {
		sms.Reset();
		running = 1;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SMSEMU));

	while(quit == 0) {

		CheckMessages();
	//	if(running)
	//		sms.Frame();
		dx7.StartBlit();
		dx7.StopBlit();
	}

	fclose(logfd);
	return(0);
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMSEMU));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_SMSEMU);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   hInst = hInstance; // Store instance handle in our global variable

   hwnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hwnd)
   {
      return FALSE;
   }

   dx7.Init(hwnd,hInst,256,240);
   dx7.Resize();

   ShowWindow(hwnd, nCmdShow);
   UpdateWindow(hwnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	char fn[_MAX_PATH] = "";
	OPENFILENAME dlgdata;
	char dir[_MAX_PATH];

	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	int statwidths[] = {200, -1};
	HWND hStatus;

	switch (message)
	{
	case WM_CREATE:
		hStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL,
			WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP, 0, 0, 0, 0,
			hWnd, (HMENU)IDC_MAIN_STATUS, GetModuleHandle(NULL), NULL);

		SendMessage(hStatus, SB_SETPARTS, sizeof(statwidths)/sizeof(int), (LPARAM)statwidths);
		SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"smsemu started.");
		break;
	case WM_SIZE:
		hStatus = GetDlgItem(hwnd, IDC_MAIN_STATUS);
		SendMessage(hStatus, WM_SIZE, 0, 0);
		dx7.Resize();
		break;
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case ID_FILE_OPEN:
			strcpy(fn,"");
			GetCurrentDirectory(_MAX_PATH,dir);
			ZeroMemory(&dlgdata,sizeof(OPENFILENAME));
			dlgdata.lStructSize = sizeof(OPENFILENAME);
			dlgdata.hwndOwner = hWnd;
			dlgdata.lpstrFilter = "sms roms (*.sms)\0*.sms\0all files (*.*)\0*.*\0";
			dlgdata.lpstrFile = fn;
			dlgdata.nMaxFile = _MAX_PATH;
			dlgdata.lpstrInitialDir = dir;
			dlgdata.lpstrTitle = "open rom";
			dlgdata.Flags = OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
			if(GetOpenFileName(&dlgdata)) {
				SendDlgItemMessage(hWnd,IDC_MAIN_STATUS,SB_SETTEXT,0,(LPARAM)"Loading ROM...");
				SendDlgItemMessage(hWnd,IDC_MAIN_STATUS,SB_SETTEXT,1,(LPARAM)fn);
				if(sms.Load(fn) == 0) {
					running = 1;
					fn[0] = 0;
					SendDlgItemMessage(hWnd,IDC_MAIN_STATUS,SB_SETTEXT,0,(LPARAM)"Loading ROM...OK");
					SendDlgItemMessage(hWnd,IDC_MAIN_STATUS,SB_SETTEXT,1,(LPARAM)fn);
					sms.Reset();
				}
			}
			break;
		case ID_VIEW_DEBUGGER:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_DEBUGGER), hWnd, DebuggerProc);
			break;
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, AboutProc);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		quit++;
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK AboutProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}

#define WM_UPDATE (WM_USER+1)

// Message handler for debugger box.
INT_PTR CALLBACK DebuggerProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	u32 i,p;
	char str[1024];

	UNREFERENCED_PARAMETER(lParam);
	switch (msg)
	{
	case WM_INITDIALOG:
//		return (INT_PTR)TRUE;
	case WM_UPDATE:
		SendDlgItemMessage(hDlg,IDC_CPUREGS,WM_SETTEXT,0,(LPARAM)sms.GenerateRegData());
		SendDlgItemMessage(hDlg,IDC_LIST1,LB_RESETCONTENT,0,0);
		p = sms.GetPC();
		for(i=0;i<25;i++) {
			p = sms.Disassemble(p,str);
			SendDlgItemMessage(hDlg,IDC_LIST1,LB_ADDSTRING,0,(LPARAM)str);
		}
		return (INT_PTR)TRUE;
	case WM_COMMAND:
		if(LOWORD(wParam) == IDC_STEP_BUTTON) {
			sms.Step();
			SendMessage(hDlg,WM_UPDATE,0,0);
			return (INT_PTR)TRUE;
		}
		if(LOWORD(wParam) == IDC_STEP10_BUTTON) {
			for(i=0;i<500000000;i++)
				sms.Step();
			SendMessage(hDlg,WM_UPDATE,0,0);
			return (INT_PTR)TRUE;
		}
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
